package sc.prototype.pfs.eventnotify.util;

import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import sc.prototype.pfs.eventnotify.model.Notice;
import sc.prototype.pfs.eventnotify.model.NotifyConfig;
import sc.prototype.pfs.eventnotify.model.NotifyContext;
import sc.prototype.pfs.eventnotify.model.ParamKey;

/**
 * 生效扩展参数获取器
 */
public class ExtensionHelper {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    public ExtensionHelper(Notice notice) {
        this(notice.getExtensions(), notice.getNotifyConfig());
    }

    public ExtensionHelper(NotifyConfig config, NotifyContext context) {
        this(context.getEvent().getExtensions(), config);
    }

    public ExtensionHelper(HashMap<String, String> eventExts, NotifyConfig config) {
        Assert.notNull(config, "生效扩展参数-参数异常：通知配置不可为空！");
        this.eventExts = eventExts;
        this.config = config;
        this.configExts = config.getExtensions();
    }

    NotifyConfig config;
    HashMap<String, String> eventExts;
    HashMap<String, String> configExts;

    public String get(ParamKey paramKey, String defaultValue, boolean toUpper) {
        String ret = null;
        String key = paramKey.getKey();
        if (eventExts != null && eventExts.containsKey(key)) {
            ret = eventExts.get(key);
        } else if (configExts != null && configExts.containsKey(key)) {
            ret = configExts.get(key);
        } else {
            ret = defaultValue;
        }
        checkPass(ret, paramKey);
        return toUpper(ret, toUpper);
    }

    public String get(ParamKey paramKey, boolean toUpper) {
        String ret = null;
        String key = paramKey.getKey();
        if (eventExts != null && eventExts.containsKey(key)) {
            ret = eventExts.get(key);
        } else if (configExts != null && configExts.containsKey(key)) {
            ret = configExts.get(key);
        } else {
            if (paramKey.isMandatory()) {
                String err = String.format("扩展参数：%s，必须，但是没有找到", paramKey);
                throw new IllegalArgumentException(err);
            }
        }
        checkPass(ret, paramKey);
        return toUpper(ret, toUpper);
    }

    public void checkPass(String ret, ParamKey paramKey) {
        if (!paramKey.checkPass(ret)) {
            String err = String.format("扩展参数：%s，配置格式错误->%s", paramKey, ret);
            throw new IllegalArgumentException(err);
        }
    }

    public String toUpper(String ret, boolean toUpper) {
        if (toUpper) {
            return ret != null ? ret.toUpperCase() : null;
        } else {
            return ret;
        }
    }
}
